use std::sync::{Arc};
use std::cell::RefCell;
use std::collections::{HashMap};
use crate::dynf::vm::{VM,DObjectRef};

#[derive(Debug, PartialEq,Clone)]
pub struct Scope {
    locals: Vec<Arc<RefCell< HashMap<String,DObjectRef>>>>,
}

impl Default for Scope {
    fn default() -> Self {
        Scope {
            locals:vec![
                Arc::new(RefCell::new(HashMap::new()))
            ]
        }
    }
}

impl Scope {
    pub fn store_name(&self, vm: &VM, key: &str, value: DObjectRef) {
       let mut dict = self.locals.first().unwrap().borrow_mut();
       dict.insert(key.to_owned(), value);
    }

    pub fn load_name(&self, vm: &VM, key: &str) -> Option<DObjectRef> {
        for dict in self.locals.iter() {
            if let Some(value) = dict.borrow().get(key) {
                return Some(value.clone());
            }
        }
        None
     }

     pub fn new_child_scope(&self) -> Scope {
         Scope {
             locals:self.locals.clone()
         }
     }

}